#!/usr/bin/Rscript
# 一个全局变量来判断，是什么操作系统
os <<- Sys.info()['sysname']

if(os == "Windows"){
  setwd("F:/cuffdiff/")
}else if(os == Linux){
  setwd("/home/zhang/BMK/test/cuffdiff/")
}

library(ReactomePA)
library(reactome.db)
library(clusterProfiler)
library(openxlsx)
library(org.Hs.eg.db)

do.reactome <- function(genelist){
  re <- enrichPathway(genelist$ENTREZID, organism = "human", pvalueCutoff = 0.05,
                pAdjustMethod = "BH", readable = T)
  # re <- setReadable(re, 'org.Hs.eg.db')
  re <- as.data.frame(re)
  return(re)
}

wb = createWorkbook()

# 处理所有差异表达的mrna的结果
mrna <- read.table("mrna/gene_exp.diff", header = T)
mrna <- mrna[mrna$significant == "yes", ]
mrna <- as.character(unique(mrna$gene))
eg <- bitr(mrna, fromType = "SYMBOL", toType = c("ENTREZID", "ENSEMBL"), OrgDb = "org.Hs.eg.db")

addWorksheet(wb, "all")
writeData(wb, 1, do.reactome(eg))

# cerna中mRNA的通路注释
mrna <- read.table("mrna.cerna")
eg <- bitr(mrna[,1], fromType = "SYMBOL", toType = c("ENTREZID", "ENSEMBL"), OrgDb = "org.Hs.eg.db")
addWorksheet(wb, "cerna_mrna")
writeData(wb, 2, do.reactome(eg))

# 所有lnc上下游300kb靶基因的各种通路注释
mrna <- read.table("lnctarget/lnc.mrnalist")
eg <- bitr(mrna[,1], fromType = "SYMBOL", toType = c("ENTREZID", "ENSEMBL"), OrgDb = "org.Hs.eg.db")
addWorksheet(wb, "all_lnc")
writeData(wb, 3, do.reactome(eg))

# 处理cerna中lnc的靶基因的结果的
lnc <- read.table("lnctarget/lnc_cerna.mrnalist")
eg <- bitr(lnc[,1], fromType = "SYMBOL", toType = c("ENTREZID", "ENSEMBL"), OrgDb = "org.Hs.eg.db")

addWorksheet(wb, "lnc")
writeData(wb, 4, do.reactome(eg))

saveWorkbook(wb, "reactomePA.xlsx")
rm(wb)

###  super 5 pathway   ######
wb = createWorkbook()
cyto <- read.xlsx("mirandaBC_superdiff.xlsx", sheet = 4, colNames = F)

y <- unique(cyto[,1])
wb = createWorkbook()

# 批量做，而且，批量生成ws，并且写入值
for(i in 1:length(y)){
  test <- cyto[cyto[,1] == as.character(y[i]) & cyto[,3] == "mrna", 2]
  eg <- bitr(test, fromType = "SYMBOL", toType = c("ENTREZID", "ENSEMBL"), OrgDb = "org.Hs.eg.db")
  kegg <- do.reactome(eg)
  addWorksheet(wb, as.character(y[i]))
  writeData(wb, as.character(y[i]),kegg)
}
saveWorkbook(wb, "superdiffreactome.xlsx", overwrite = T)

rm(wb)
